from datetime import datetime
from typing import Optional

from pydantic import Field

from app.models.TSModel import TSModel
from app.models.device_info import DeviceInfo
from app.utils import get_current_time


class UserToken(TSModel):

    @staticmethod
    def generate_rowkey(phone_number: str, user_id: str) -> str:
        return f"{phone_number[::-1]}oc{user_id}"

    def get_row_key(self):
        return self.generate_rowkey(self.phone_number, self.user_id)

    __INSTANCE_NAME__: bytes = "flow_guardian".encode('utf-8')
    __TABLE_NAME__: bytes = "user_token_info".encode('utf-8')
    phone_number: str
    platform: Optional[str] = 'onethingcloud'
    user_id: str
    access_key: str
    access_key_expires: str
    refresh_key: str
    refresh_key_expires: str
    create_datetime: Optional[str] = Field(default_factory=get_current_time)
    last_datetime: Optional[str] = Field(default_factory=get_current_time)

    @classmethod
    def from_data(cls, external_data):
        field_mapping = {
            'phone': 'phone_number',
            'userid': 'user_id',
            'ak': 'access_key',
            'akExp': 'access_key_expires',
            'rk': 'refresh_key',
            'rkExp': 'refresh_key_expires'
        }
        data = {value: str(external_data.get(key)) for key, value in field_mapping.items()}
        return cls(**data)

    @classmethod
    def from_device_info(cls, device_info: DeviceInfo):
        return cls(
            phone_number=device_info.phone_number,
            platform=device_info.platform,
            user_id=device_info.user_id,
            access_key=device_info.access_key,
            access_key_expires=device_info.access_key_expires,
            refresh_key=device_info.refresh_key,
            refresh_key_expires=device_info.refresh_key_expires
        )
